package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.SpotContent;
import cn.wolfcode.wolf2w.queryObject.SpotContentQueryObject;
import cn.wolfcode.wolf2w.repository.DestinationRepository;
import cn.wolfcode.wolf2w.repository.SpotContentRepository;
import cn.wolfcode.wolf2w.service.ISpotContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class SoptContentServiceImpl implements ISpotContentService {

    @Autowired
    private SpotContentRepository spotContentRepository;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private DestinationRepository destinationRepository;

    @Override
    public void save(SpotContent spotContent) {
        // 以防万一把要保存的对象的id设置为空
        spotContent.setId(null);
        spotContentRepository.save(spotContent);
    }

    @Override
    public void update(SpotContent spotContent) {
        spotContentRepository.save(spotContent);
    }

    @Override
    public void delete(String id) {
        spotContentRepository.deleteById(id);
    }

    @Override
    public SpotContent get(String id) {
        Optional<SpotContent> spotContent = spotContentRepository.findById(id);
        return spotContent.orElse(null);
    }

    @Override
    public List<SpotContent> list() {
        List<SpotContent> all = spotContentRepository.findAll();
        return all;
    }

    @Override
    public Page<SpotContent> query(SpotContentQueryObject qo) {

        // 封装查询条件
        Query query = new Query();

        // 总条数
        long totalCount = template.count(query, SpotContent.class);

        // 如果总条数为0 , 那么返回空的分页对象
        if (totalCount==0){
            return Page.empty();
        }

        // 分页对象 , 参数1为当前页 从0开始 , 参数2为每页显示条数 , 参数3为排序方式, 参数4为按哪个字段排序
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(),
                Sort.Direction.ASC,"id");

        query.with(pageable);// 添加查询条件

        List<SpotContent> list = template.find(query, SpotContent.class);

        // PageImpl 为 Page 接口的一个实现类
        return new PageImpl<>(list, pageable,totalCount );
    }


}
